/*
 * Copyright the original author or authors.
 * 
 * Licensed under the MOZILLA PUBLIC LICENSE, Version 1.1 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *	  http://www.mozilla.org/MPL/MPL-1.1.html
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.googlecode.milib.display.libraryItems {
	import flash.display.DisplayObject;
	import flash.display.MovieClip;
	import flash.events.EventDispatcher;
	import flash.utils.Dictionary;

	/**
	 * @author Marek Brun
	 */
	public class MCDetector extends EventDispatcher {
		
		private var mc:MovieClip;
		private static const servicedObjects : Dictionary = new Dictionary(true);
		
		public function MCDetector(access:Private, mc:MovieClip) {
			this.mc=mc;
			
		}
		
		private function setMCCreated(mc:MCDetectable):void {
			dispatchEvent(new MCDetectEvent(MCDetectEvent.MOVIECLIP_CREATED, mc));
		}
		
		private function setMCRemoved(mc:MCDetectable):void {
			dispatchEvent(new MCDetectEvent(MCDetectEvent.MOVIECLIP_REMOVED, mc));
		}
		
		static public function dispatchWithParentMainMCMCEnter(mc:MCDetectable):void {
			var inspector:MCDetector=findParentMainMCInspector(mc);
			if(inspector){
				inspector.setMCCreated(mc);
			}
		}
		
		static public function dispatchWithParentMainMCMCOut(mc:MCDetectable):void {
			var inspector:MCDetector=findParentMainMCInspector(mc);
			if(inspector){
				inspector.setMCRemoved(mc);
			}
		}
		
		static public function findParentMainMCInspector(mc:MCDetectable):MCDetector {
			var count:uint=0;
			var parent:DisplayObject=mc;
			while(parent.parent && parent.parent is MovieClip){
				if(hasInstance(MovieClip(parent.parent))){
					return forInstance(MovieClip(parent.parent));
					break;
				}
				parent=parent.parent;
				count++;
				if(count>200){ break; }
			}
			return null;
		}
		
		static public function hasInstance(mc:MovieClip):Boolean {
			return Boolean(servicedObjects[mc]);
		}
		
		static public function forInstance(mc:MovieClip):MCDetector {
			if(servicedObjects[mc]){
				return servicedObjects[mc];
			}else{
				servicedObjects[mc]=new MCDetector(null, mc);
				return servicedObjects[mc];
			}
		}
		
	}
}
internal class Private{}
